package cn.az13js.satool;

import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;

public class WriteACSVFile {

    public static void write(String fileName, String lineDatas) throws IOException {
        FileWriter csv = new FileWriter(fileName, true);
        csv.write(lineDatas += "\n");
        csv.close();
    }

    public static void write(String fileName, double[] lineDatas) throws IOException {
        String lineText = "";
        for (double element : lineDatas) {
            if (!lineText.isEmpty()) {
                lineText += ",";
            }
            lineText += String.valueOf(element);
        }
        write(fileName, lineText);
    }

    public static void write(String fileName, double[][] datas) throws IOException {
        FileWriter csv = new FileWriter(fileName);
        DecimalFormat formater = new DecimalFormat("0.000000000");
        int blockSize = 64 * 1024;
        StringBuilder fileContents = new StringBuilder(blockSize);
        boolean isLineStart;
        for (double[] lineData : datas) {
            isLineStart = true;
            for (double data : lineData) {
                if (isLineStart) {
                    isLineStart = false;
                } else {
                    fileContents.append(",");
                    if (fileContents.length() > blockSize - 1024) {
                        csv.write(fileContents.toString());
                        fileContents.setLength(0);
                    }
                }
                fileContents.append(formater.format(data));
                if (fileContents.length() > blockSize - 1024) {
                    csv.write(fileContents.toString());
                    fileContents.setLength(0);
                }
            }
            fileContents.append("\n");
            if (fileContents.length() > blockSize - 1024) {
                csv.write(fileContents.toString());
                fileContents.setLength(0);
            }
        }
        if (fileContents.length() > 0) {
            csv.write(fileContents.toString());
        }
        csv.close();
    }

    public static void write1DArray(String fileName, double[] data) throws IOException {
        FileWriter csv = new FileWriter(fileName);
        int blockSize = 32 * 1024;
        StringBuilder fileContents = new StringBuilder(blockSize);
        DecimalFormat formater = new DecimalFormat("0.000000000");
        for (double item : data) {
            fileContents.append(formater.format(item));
            fileContents.append("\n");
            if (fileContents.length() > blockSize - 10) {
                csv.write(fileContents.toString());
                fileContents.setLength(0);
            }
        }
        if (fileContents.length() > 0) {
            csv.write(fileContents.toString());
        }
        csv.close();
    }
}
